<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <backView />
    <text class="block text-[48rpx] font-extrabold mb-[40rpx] text-center text-blue-600 drop-shadow">{{PageItem.title}}详情</text>
    <FormView v-if="form" :fieldConfig="fieldConfig" :form="form" :showButtons="false" @submit="submitForm" />
    
    <!-- 操作按钮 -->
    <view class="mt-[48rpx] flex gap-[24rpx]">
      <nut-button block type="default" class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow flex-1" @click="goBack">返回</nut-button>
      <nut-button block type="primary" class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow flex-1 bg-blue-500 hover:bg-blue-600 active:bg-blue-700" @click="goEdit">编辑</nut-button>
      <nut-button block type="danger" class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow flex-1" @click="deleteRecord">删除</nut-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { emergencyContactFields as fieldConfig } from './fields'
import FormView from '@/components/FormView.vue'
import { request } from '@/service/request'
import { PageItem } from './fields'
import backView from '@/components/backView.vue'

const form = ref<any>({})
const recordId = ref<string>('')

onMounted(async () => {
  // 获取路由参数
  const params = Taro.getCurrentInstance().router?.params
  if (params?.id) {
    recordId.value = params.id
    await loadRecordData(params.id)
  }
})

async function loadRecordData(id: string) {
  try {
    const result = await request.get<any>(`${PageItem.commUrl}/queryById?id=${id}`, {}, {
      useErrMsg: true
    })

    console.log("result", result)
    
    if (result.success) {
      form.value = result.success
    }
  } catch (error) {
    console.error('加载记录失败:', error)
    Taro.showToast({ title: '加载记录失败', icon: 'error' })
  }
}

function submitForm(form: any, fieldConfig: any) {
  // 查看页面不需要提交
}

function goBack() {
  Taro.navigateBack()
}

function goEdit() {
  if (recordId.value) {
    Taro.navigateTo({
      url: `./edit?id=${recordId.value}`
    })
  }
}

async function deleteRecord() {
  try {
    const { confirm } = await Taro.showModal({
      title: '确认删除',
      content: '确定要删除记录吗？',
      confirmText: '删除',
      cancelText: '取消'
    })
    
    if (confirm && recordId.value) {
      const result = await request.delete<any>(`${PageItem.commUrl}/delete?id=${recordId.value}`, {}, {
        useErrMsg: true
      })
      
      if (result) {
        Taro.showToast({ title: '删除成功', icon: 'success' })
        setTimeout(() => {
          Taro.navigateBack()
        }, 1500)
      }
    }
  } catch (error) {
    console.error('删除失败:', error)
    Taro.showToast({ title: '删除失败', icon: 'error' })
  }
}
</script>
